//
//  ALPListonListMoreVC.m
//  AlpFM
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 Alp. All rights reserved.
//

#import "ALPListonListMoreVC.h"
#import "ALPAppTools.h"
#import "ALPListenListMoreModel.h"
#import "ALPListenListMoreCell.h"
#import "ALPListenListDetailsVC.h"
#import "ALPEditorPlayVC.h"
#import "MJRefresh.h"

@interface ALPListonListMoreVC ()<UITableViewDataSource,UITableViewDelegate,ALPListenListMoreCellDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong) NSMutableDictionary *bigDic;
@property (nonatomic, copy) NSString *lastKey;
@property (nonatomic, strong) NSMutableArray *keyArray; //用来装找大字典里key值
@property (nonatomic, assign)NSInteger nextPage;
@property (nonatomic, assign)NSInteger isUpLoading;
@end

@implementation ALPListonListMoreVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.strTitle;
    //取消渲染
    UIImage *image3 = [UIImage imageNamed:@"fanhuijiantou1"];
    image3 = [image3 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem  =[[UIBarButtonItem alloc]initWithImage:image3 style:UIBarButtonItemStylePlain target:self action:@selector(fanhui:)];
    
    self.keyArray = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    self.bigDic = [NSMutableDictionary dictionary];
    
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 603) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource  =  self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone; //取消分割线
    [self.view addSubview:self.myTableView];
    
    [self.myTableView registerClass:[ALPListenListMoreCell class] forCellReuseIdentifier:@"cell"];
    
    [self addHeader];
    [self addFooter];
//    //时间戳
//    NSString *str=@"1456217863";//时间戳
//    NSTimeInterval time=[str doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
//    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
//    NSLog(@"date:%@",[detaildate description]);
//    //实例化一个NSDateFormatter对象
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    //设定时间格式,这里可以设置成自己需要的格式
//    [dateFormatter setDateFormat:@"MM-dd-yyyy"];
//    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
//    NSLog(@"***%@",currentDateStr);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *array = [self.bigDic objectForKey:[self.keyArray objectAtIndex:indexPath.section]];
    return array.count * 78 + 44;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   NSArray *array = [self.bigDic allKeys];
    return array.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ALPListenListMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.xieyiren = self;
    //传数组确定cell个数
   NSMutableArray *array = [self.bigDic objectForKey:[self.keyArray objectAtIndex:indexPath.section]];
    cell.array = array;
    cell.titleStr = [self.keyArray objectAtIndex:indexPath.section];;
    //传model
    cell.model = [self.allArray objectAtIndex:indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [tableView deselectRowAtIndexPath:indexPath animated:NO];  //取消选中状态
}





-(void)pushDetailVC:(NSInteger)specialId contentType:(NSInteger)contentType indexPath:(NSInteger)indexPath{
    if (contentType == 1) {
        ALPEditorPlayVC *VC = [[ALPEditorPlayVC alloc]init];
        VC.indice = indexPath;
        VC.idid = specialId;
        VC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:VC animated:YES completion:^{
            
            
        }];
    }else{
        ALPListenListDetailsVC *VC = [[ALPListenListDetailsVC alloc]init];
        VC.specialId = specialId;
        [self.navigationController pushViewController:VC animated:YES];
    }
}


#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block ALPListonListMoreVC *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block ALPListonListMoreVC *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}

-(void)GetPersonList:(NSInteger)page{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/subject_list?device=android&page=%ld&per_page=10&title=更多",page];
    [ALPAppTools getWithAFNurl:str block:^(id result) {
        if (self.isUpLoading == NO) {
            [self.allArray removeAllObjects];
        }
        
        
        NSMutableArray *array = [result objectForKey:@"list"];
        for (NSMutableDictionary *dic in array) {
            ALPListenListMoreModel *mol = [[ALPListenListMoreModel alloc]init];
            [mol setValuesForKeysWithDictionary:dic];
            
            //时间戳
            NSString *str= [NSString stringWithFormat:@"%ld",mol.releasedAt / 1000];
            NSTimeInterval time=[str doubleValue];
            NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
            //      NSLog(@"date:%@",[detaildate description]);
            //实例化一个NSDateFormatter对象
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //设定时间格式,这里可以设置成自己需要的格式
            [dateFormatter setDateFormat:@"MM-dd-yyyy"];
            NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
            
            if ([self.lastKey isEqualToString:currentDateStr]) {
                NSMutableArray *arr = [self.bigDic objectForKey:currentDateStr];
                
                [arr addObject:mol];
            }else{
                
                NSMutableArray *arr1 = [NSMutableArray array];
                [arr1 addObject:mol];
                [self.bigDic setObject:arr1 forKey:currentDateStr];
                self.lastKey = currentDateStr;
                
                [self.keyArray addObject:currentDateStr];
                
            }
            
            [self.allArray addObject:mol];
        }
        [self.myTableView footerEndRefreshing];
        [self.myTableView headerEndRefreshing];
        [self.myTableView reloadData];
    } error:^(NSError *error) {
        
        
    }];
}





-(void)fanhui:(UIBarButtonItem *)btn{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
